package com.heima.appgateway.filter;

import com.heima.appgateway.utils.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @projectName: heima-leadnews
 * @package: com.heima.appgateway.filter
 * @className: AuthenticationFilter
 * @author: Eric
 * @description: TODO
 * @date: 2023/11/3 15:21
 * @version: 1.0
 */
@Component
public class AuthenticationFilter implements GlobalFilter, Ordered {

    public static final String TOKEN = "token";

    /**
     * 过滤器
     *
     * @param exchange 交易所
     * @param chain    链条
     * @return {@link Mono}<{@link Void}>
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 如果当前请求如果是登录,就放行
        if (request.getPath().toString().contains("/user/api/v1/login/login_auth")){
            return chain.filter(exchange);
        }
        // 获取token请求头
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(TOKEN);
        // 校验请求头,如果为空或者不合法 --返回401
        if (StringUtils.isEmpty(token) || !AppJwtUtil.verifyToken(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED); // 枚举,HttpStatus封装的
            return response.setComplete();
        }
        // 合法就放行
        return chain.filter(exchange);
    }

    // 设置优先级
    @Override
    public int getOrder() {
        return 0;
    }
}
